package com.example.diarymanger.controller;

import com.example.diarymanger.bean.ApiResponse;
import com.example.diarymanger.bean.DiaryBean;
import com.example.diarymanger.config.UploadConfig;
import com.example.diarymanger.service.DiaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Collections;
import java.util.List;
import java.util.NoSuchElementException;

@RestController
@RequestMapping("/diary")
public class DiaryController {

    @Autowired
    private DiaryService diaryService;

    @Autowired
    private UploadConfig uploadConfig;

    /**
     * 保存日记功能，并且required = false允许前端不上传图片
     *
     * @param files
     * @param diaryBean
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/saveDiary", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<ApiResponse> saveDiary(@RequestParam(value = "files", required = false) List<MultipartFile> files,
                                                 @ModelAttribute DiaryBean diaryBean) throws IOException {
        // 确保上传目录存在
//        MultipartFile String uploadDir = uploadConfig.getPath();
//        Files.createDirectories(Paths.get(uploadDir));
//        for ( file : files) {
//            if (!file.isEmpty()) {
//                try {
//                    byte[] bytes = file.getBytes();
//                    Path path = Paths.get(uploadDir, file.getOriginalFilename());
//                    Files.write(path, bytes);
//
//                    String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
//                            .path("/uploads/")
//                            .path(file.getOriginalFilename())
//                            .toUriString();
//                    // 更新diaryBean中的图片链接
//                    if (diaryBean.getImageLink() == null || diaryBean.getImageLink().isEmpty()) {
//                        diaryBean.setImageLink(fileDownloadUri);
//                    } else {
//                        diaryBean.setImageLink(diaryBean.getImageLink() + "," + fileDownloadUri);
//                    }
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    return "Failed to upload file: " + file.getOriginalFilename();
//                }
//            }
//        }
//        System.out.println(111);
//        ResponseEntity<ApiResponse> response = diaryService.saveDiary(diaryBean);
//        System.out.println(response);
//        return "Diary saved successfully";
        String uploadDir = "D:\\IDEA-Project\\schoolProject\\Diary-manger\\Diary-manger\\imagePath";
        Files.createDirectories(Paths.get(uploadDir));

        StringBuilder imageLinks = new StringBuilder();

        if (files != null && !files.isEmpty()) {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    try {
                        // 获取文件名并构建保存路径
                        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
                        Path path = Paths.get(uploadDir, fileName);
                        // 保存文件到指定路径
                        Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
                        // 构建文件下载URI
//                    String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
//                            .path("/uploads/")
//                            .path(fileName)
//                            .toUriString();

                        // 将文件下载URI添加到imageLinks
                        // 构建相对文件下载URI
                        // 注意：这里返回的是相对路径，而非完整URL
                        String relativeFileDownloadUri = "/uploads/" + fileName;

                        if (imageLinks.length() > 0) {
                            imageLinks.append(","); // 如果不是第一个链接，则添加逗号作为分隔符
                        }
                        imageLinks.append(relativeFileDownloadUri);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return new ResponseEntity<>(new ApiResponse(false, "Failed to upload file: " + file.getOriginalFilename()), HttpStatus.INTERNAL_SERVER_ERROR);
                    }
                }
            }
        }

        System.out.println("imageLink=[" + imageLinks + "]");
        // 设置图片链接到diaryBean
        diaryBean.setImageLink(imageLinks.toString());

        // 调用服务层保存日记
        ResponseEntity<ApiResponse> response = diaryService.saveDiary(diaryBean);

        // 返回响应结果
        if (response.getBody().isSuccess()) {
            return new ResponseEntity<>(new ApiResponse(true, "Diary saved successfully"), HttpStatus.CREATED);
        } else {
            return new ResponseEntity<>(new ApiResponse(false, "Failed to save diary"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    // 辅助函数：获取文件扩展名
    private String getFileExtension(String filename) {
        if (filename != null && filename.contains(".")) {
            return filename.substring(filename.lastIndexOf("."));
        }
        return "";
    }

    @GetMapping("/selectDiaryAll")
    public ResponseEntity<List<DiaryBean>> getDiariesByUserId(@RequestParam Long userId) {
        return diaryService.getDiariesByUserId(userId);
    }

    /**
     * 根据diaryId查询日记
     * @param diaryId
     * @return
     */
    @GetMapping("/selectDiaryByDiaryId/{diaryId}")
    public ResponseEntity<DiaryBean> getDiaryByDiaryId(@PathVariable Integer diaryId) {
        try {
            DiaryBean diaryBean = diaryService.getDiaryByDiaryId(diaryId);
            return new ResponseEntity<>(diaryBean, HttpStatus.OK);
        } catch (NoSuchElementException e) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 根据diaryId更新日记
     * @param diaryId
     * @param diaryBean
     * @param images
     * @param files
     * @return
     * @throws IOException
     */
    @PutMapping(value = "/updateDiaryById/{diaryId}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> updateDiaryWithFiles(
            @PathVariable Integer diaryId,
            @ModelAttribute DiaryBean diaryBean,
            @RequestParam(value = "images", required = false) List<MultipartFile> images,
            @RequestParam(value = "files", required = false) List<MultipartFile> files) throws IOException {

        if (diaryId == null || !diaryId.equals(diaryBean.getDiaryId())) {
            return new ResponseEntity<>("Invalid diary ID", HttpStatus.BAD_REQUEST);
        }
        // 处理图片上传
        StringBuilder imageLinks = new StringBuilder();
        if (images != null && !images.isEmpty()) {
            for (MultipartFile image : images) {
                if (!image.isEmpty()) {
                    String fileName = image.getOriginalFilename();
                    File dest = new File(uploadConfig.getPath() + fileName); // 使用配置的路径
                    image.transferTo(dest);

                    if (imageLinks.length() > 0) {
                        imageLinks.append(","); // 如果有多个图片链接，用逗号分隔
                    }
                    imageLinks.append(dest.getAbsolutePath()); // 或者仅保存文件名，根据需求调整
                }
            }
            diaryBean.setImageLink(imageLinks.toString()); // 更新日记对象中的图片链接字段
        }

        boolean isUpdated = diaryService.updateDiary(diaryBean);
        if (isUpdated) {
            return new ResponseEntity<>("Diary updated successfully", HttpStatus.OK);
        } else {
            return new ResponseEntity<>("Failed to update diary", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @DeleteMapping("/delete/{diaryId}")
    public String deleteDiary(@PathVariable Integer diaryId) {
        boolean isDeleted = diaryService.deleteByDiaryId(diaryId);
        if (isDeleted) {
            System.out.println("删除成功");
            return "删除成功";
        } else {
            System.out.println("删除失败");
            return "删除失败";
        }
    }

    @GetMapping(value = "/selectIsPublicDiaryAll")
    public ResponseEntity<List<DiaryBean>> getIsPublicDiaryAll(){
        try {
            // 调用服务层方法获取所有公开的日记
            return diaryService.getIsPublicDiaryAll();
        } catch (Exception e) {
            // 捕获异常并返回错误响应
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.emptyList());
        }
    }
}
